package com.itheima.dianming.aop;

import cn.hutool.core.util.NumberUtil;
import com.itheima.dianming.exception.BusinessException;
import com.itheima.dianming.util.Cmder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

@Component
@Aspect
@Slf4j
public class AuthAdvice {

    @Pointcut("execution(* *.*(..))")
    public void pt(){}

    @Before("@annotation(hasAuth)")
    public void before(HasAuth hasAuth){
        log.info("权限校验开始》》》###############################################");
        String roleName = hasAuth.value();
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        if(authorities!=null){
            for (GrantedAuthority authority : authorities) {
                if(authority.getAuthority().equals(roleName)){
                    log.info("有权操作");
                    return;
                }
            }
        }
        throw new BusinessException("抱歉，无权操作！");
    }

    @After("execution(* com.itheima.dianming.controller.CommonController.runProject(..))")
    public void after(){
        log.info("==========>重要！！开始清理残余程序！！");
        //释放资源
        try {
            //检查是否有git程序
            Integer git = Cmder.getPid("git");
            if(git!=null){
                log.info("==========>重要！！开始清理残余程序！！git：{}",git);
                Cmder.killPid(git);
            }
            //检查8080端口，并杀死对应的进程
            Integer port = Cmder.getPid(8080);
            if(port!=null){
                log.info("==========>重要！！开始清理残余程序！！tomcat：{}",port);
                Cmder.killPid(port);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        Integer port = Cmder.getPid(8080);
        if(port!=null){
            Cmder.killPid(port);
        }
    }
}
